const express = require("express");
const multer = require("multer"); // 用于处理文件上传
const fs = require("fs"); // 用于文件操作
const app = express();
const path = require("path");
const cors = require("cors");
const { resetFileDir } = require("./utils");
const { pdfRead, xlsRead } = require("./utils");
const { baseUrl } = require("./env");

const resourcePath = "uploads/";
const resultPath = "result/";

const wordsPath = path.resolve(__dirname, "译林版单词表.xls");

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, resourcePath); // 存储上传的文件的目录
  },
  filename: (req, file, cb) => {
    cb(null, file.originalname);
  },
});

const upload = multer({
  storage,
  fileFilter: (req, file, cb) => {
    file.originalname = Buffer.from(file.originalname, "latin1").toString(
      "utf-8"
    );
    cb(null, true);
  },
});

app.use(express.json());
app.use(cors());

// 清空历史数据
app.use((req, res, next) => {
  if (req.url.includes("/upload")) {
    resetFileDir(resourcePath);
    resetFileDir(resultPath);
  }
  next();
});

// 上传
app.post("/upload", upload.array("files", 5), (req, res) => {
  const uploadedFiles = req.files;

  // 下载文件目录
  let resultFiles = [];

  for (const file of uploadedFiles) {
    const filePath = `${resourcePath}/${file.filename}`;
    const fileName = file.filename.split(".")[0];
    resultFiles.push({
      name: fileName + ".xlsx",
      url: baseUrl + "/download/" + fileName + ".xlsx",
    });

    const result = xlsRead(wordsPath);
    pdfRead(result, filePath, fileName);
  }

  // 返回处理后的文件路径
  res.json({ downloadFiles: resultFiles });
});

// 下载
app.get("/download/:fileName", (req, res) => {
  const fileName = req.params.fileName;
  const filePath = path.join(__dirname, resultPath, fileName);

  // 检查文件是否存在
  if (fs.existsSync(filePath)) {
    res.download(filePath, fileName); // 发送文件给客户端以进行下载
  } else {
    res.status(404).send("File not found");
  }
});

const port = 4001;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
